import { useUserStore } from "@/stores";
import { useStorage } from "./storage";

let baseHOST = 'https://xcyd.kf.kaifa.cc/app/ycAivdo/';
let baseURL = `${baseHOST}api/`;

import system from './mp-weixin/system';
if (system.isProd()) {
	baseHOST = `${system.host()}/app/ycAivdo/`;
	baseURL = `${system.host()}/app/ycAivdo/api/`;
}
const RequestHeaders = (options ?: any) => {
	const header : any = {};
	const { getToken, hasLogin } = useUserStore();
	if (hasLogin()) {
		header['Authorization'] = getToken();
	}
	if (options && options.header) {
		for (let x in options.header) {
			header[x] = options.header[x]
		}
	}
	const storeage = useStorage();
	const appid = system.appid();
	if (appid) {
		header['Appid'] = appid;
		const icode = storeage.get('ICODE.' + appid);
		if (icode) {
			header['Icode'] = icode;
		}
		const PUID = storeage.get('PUID.' + appid);
		if (PUID) {
			header['Puid'] = PUID;
		}
	}
	header['content-type'] = 'application/json';
	header['Accept'] = 'application/json, text/plain, */*';
	return header;
}
export const $http = {
	ResponseCode: {
		SUCCESS: 200,
		NEED_LOGIN: 12000,
		PAY_SUCCESS: 9000,
		PAY_NOTPAY: 11000,
		NEED_PAY: 60000
	},
	baseURL,
	baseHOST,
	get: (url : string, options ?: any) : Promise<any> => {
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				header: RequestHeaders(options),
				url: baseURL + url,
				success: (res : any) => {
					let data = res.data
					if (data.code == 200) {
						resolve(res.data);
					}
					if (data.code == 404) {
						uni.hideLoading()
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
					}
					reject(res);

				},
				fail: (err : any) => {
					reject(err);
				},
				complete: () => { }
			})
		})
	},
	post: (url : string, options : any) : Promise<any> => {
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				header: RequestHeaders(options),
				url: baseURL + url,
				method: 'POST',
				success: (res : any) => {
					let data = res.data
					if (data.code == 200) {
						resolve(res.data);
					}
					if (data.code == 404) {
						uni.hideLoading()
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
						reject(res);
					}else{
						reject(res);
					}
					
				},
				fail: (err : any) => {
					reject(err);
				},
				complete: () => { }
			})
		})
	},
	upload: (url : string, options : any) : UniApp.UploadTask | Promise<any> => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				...options,
				header: RequestHeaders(options),
				url: baseURL + url,
				success: (res : any) => {
					if (res.statusCode === 200) {
						resolve(JSON.parse(res.data));
					} else {
						reject(res);
					}
				},
				fail: (err : any) => {
					reject(err);
				},
			})
		})
	}
}